import { BrowserWindow, webContents } from 'electron';

/**
 * 开发者工具配置选项
 */
export interface DevToolsOptions {
  /**
   * 是否启用开发者工具
   * @default process.env.NODE_ENV !== 'production'
   */
  enabled?: boolean;

  /**
   * 是否在启动时自动打开开发者工具
   * @default false
   */
  openAtStartup?: boolean;

  /**
   * 开发者工具窗口的初始位置
   * @default 'right'
   */
  mode?: 'right' | 'bottom' | 'undocked' | 'detach';

  /**
   * 是否启用网络请求监控
   * @default true
   */
  networkMonitoring?: boolean;

  /**
   * 是否启用性能监控
   * @default true
   */
  performanceMonitoring?: boolean;

  /**
   * 是否记录 IPC 通信日志
   * @default true
   */
  logIpcMessages?: boolean;

  /**
   * 要安装的额外开发者工具扩展路径
   */
  extensions?: string[];
}

/**
 * 开发者工具管理类
 */
export class DevTools {
  private options: DevToolsOptions;
  private ipcLogs: { channel: string, args: any[], timestamp: number, direction: 'main->renderer' | 'renderer->main' }[] = [];

  /**
   * 创建开发者工具管理实例
   * @param options 开发者工具选项
   */
  constructor(options: DevToolsOptions = {}) {
    this.options = {
      enabled: process.env.NODE_ENV !== 'production',
      openAtStartup: false,
      mode: 'right',
      networkMonitoring: true,
      performanceMonitoring: true,
      logIpcMessages: true,
      extensions: [],
      ...options
    };
  }

  /**
   * 为窗口设置开发者工具
   * @param window 目标窗口或 webContents
   */
  public setup(window: BrowserWindow | Electron.WebContents): void {
    if (!this.options.enabled) return;

    const contents = window instanceof BrowserWindow ? window.webContents : window;

    // 安装开发者工具扩展
    this.installExtensions();

    // 配置开发者工具
    if (this.options.openAtStartup) {
      contents.openDevTools({ mode: this.options.mode });
    }

    // 启用网络监控
    if (this.options.networkMonitoring) {
      this.setupNetworkMonitoring(contents);
    }

    // 启用性能监控
    if (this.options.performanceMonitoring) {
      this.setupPerformanceMonitoring(contents);
    }

    // 注入辅助脚本
    this.injectHelperScripts(contents);
  }

  /**
   * 安装开发者工具扩展
   */
  private async installExtensions(): Promise<void> {
    if (!this.options.extensions || this.options.extensions.length === 0) return;

    try {
      // 安装指定的扩展
      for (const extension of this.options.extensions) {
        try {
          // 使用 electron 的 session API 安装扩展
          await BrowserWindow.defaultSession.loadExtension(extension);
          console.log(`开发者工具扩展已加载: ${extension}`);
        } catch (error) {
          console.error(`无法加载开发者工具扩展 ${extension}:`, error);
        }
      }
    } catch (error) {
      console.error('安装开发者工具扩展失败:', error);
    }
  }

  /**
   * 设置网络监控
   * @param contents WebContents 实例
   */
  private setupNetworkMonitoring(contents: Electron.WebContents): void {
    // 监听网络请求
    contents.session.webRequest.onBeforeRequest((details, callback) => {
      // 记录请求信息
      if (details.resourceType === 'xhr' || details.resourceType === 'fetch') {
        console.debug(`[Network] ${details.method} ${details.url}`);
      }
      callback({});
    });

    // 监听请求完成
    contents.session.webRequest.onCompleted((details) => {
      if (details.resourceType === 'xhr' || details.resourceType === 'fetch') {
        console.debug(`[Network] Completed ${details.method} ${details.url} (${details.statusCode})`);
      }
    });

    // 监听请求错误
    contents.session.webRequest.onErrorOccurred((details) => {
      if (details.resourceType === 'xhr' || details.resourceType === 'fetch') {
        console.error(`[Network] Error ${details.method} ${details.url} - ${details.error}`);
      }
    });
  }

  /**
   * 设置性能监控
   * @param contents WebContents 实例
   */
  private setupPerformanceMonitoring(contents: Electron.WebContents): void {
    // 周期性收集性能指标
    const interval = setInterval(() => {
      if (contents.isDestroyed()) {
        clearInterval(interval);
        return;
      }

      contents.getProcessMemoryInfo().then(memoryInfo => {
        console.debug('[Performance] Memory Usage:', {
          private: this.formatBytes(memoryInfo.private),
          shared: this.formatBytes(memoryInfo.shared),
          total: this.formatBytes(memoryInfo.total)
        });
      }).catch(e => {
        // 忽略错误
      });
    }, 30000); // 每30秒收集一次数据

    // 清理
    contents.on('destroyed', () => {
      clearInterval(interval);
    });
  }

  /**
   * 向渲染进程注入帮助脚本
   * @param contents WebContents 实例
   */
  private injectHelperScripts(contents: Electron.WebContents): void {
    contents.on('did-finish-load', () => {
      contents.executeJavaScript(`
        // 控制台增强
        console.boltronInfo = function(...args) {
          console.info('%c[Boltron]', 'color: #3498db; font-weight: bold;', ...args);
        };
        
        // 添加性能监控辅助工具
        window.__BOLTRON_DEV__ = {
          measurePerformance: function(name, callback) {
            const start = performance.now();
            const result = callback();
            const end = performance.now();
            console.info(\`[Performance] \${name}: \${(end - start).toFixed(2)}ms\`);
            return result;
          },
          logMemoryUsage: function() {
            if (performance.memory) {
              console.info('[Memory]', {
                totalJSHeapSize: this.formatBytes(performance.memory.totalJSHeapSize),
                usedJSHeapSize: this.formatBytes(performance.memory.usedJSHeapSize),
                jsHeapSizeLimit: this.formatBytes(performance.memory.jsHeapSizeLimit)
              });
            } else {
              console.info('[Memory] Performance memory API not available');
            }
          },
          formatBytes: function(bytes, decimals = 2) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const dm = decimals < 0 ? 0 : decimals;
            const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
          }
        };
        
        console.boltronInfo('开发者工具增强已加载');
      `).catch(console.error);
    });
  }

  /**
   * 记录 IPC 消息
   * @param channel IPC 通道名称
   * @param args 参数列表
   * @param direction 通信方向
   */
  public logIpcMessage(channel: string, args: any[], direction: 'main->renderer' | 'renderer->main'): void {
    if (!this.options.logIpcMessages) return;

    const log = {
      channel,
      args,
      timestamp: Date.now(),
      direction
    };

    this.ipcLogs.push(log);

    // 保留最近的1000条记录
    if (this.ipcLogs.length > 1000) {
      this.ipcLogs.shift();
    }

    console.debug(`[IPC] ${direction === 'main->renderer' ? '→' : '←'} ${channel}`, ...args);
  }

  /**
   * 获取 IPC 通信日志
   * @returns IPC 日志数组
   */
  public getIpcLogs() {
    return [...this.ipcLogs];
  }

  /**
   * 清空 IPC 通信日志
   */
  public clearIpcLogs(): void {
    this.ipcLogs = [];
  }

  /**
   * 格式化字节大小
   * @param bytes 字节数
   * @param decimals 小数位数
   * @returns 格式化后的字符串
   */
  private formatBytes(bytes: number, decimals = 2): string {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  }
} 